package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.dao.OrganDao;
import com.moyuer.bsf.domain.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.DormitoriesDao;
import tech.yunland.shop.domain.dao.LessonsDao;
import tech.yunland.shop.domain.dao.UserDormitoriesDao;
import tech.yunland.shop.domain.model.UserDormitories;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * Created by v on 17-7-3.
 */
@Service
public class UserDormitoriesServiceImpl implements UserDormitoriesService {

    @Autowired
    private DormitoriesDao dormitoriesDao;

    @Autowired
    private UserDormitoriesDao userDormitoriesDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Integer getStuSize(String did) {
        String sql =
                "select count(1) counts\n" +
                        "FROM bsf_users bu\n" +
                        "WHERE id IN (SELECT ud.students_id\n" +
                        "             FROM user_dormitories ud\n" +
                        "             WHERE ud.dormitories_id = '" + did + "')";
        int counts = ((BigInteger) userDao.findUniqueBySQL(sql).get("counts")).intValue();
        return counts;
    }

    @Override
    public List<Map<String, Object>> get(String did, Integer startIdx, Integer rows) {
        String sql =
                "SELECT *\n" +
                        "FROM bsf_users bu\n" +
                        "WHERE id IN (SELECT ud.students_id\n" +
                        "             FROM user_dormitories ud\n" +
                        "             WHERE ud.dormitories_id = '" + did + "')";
        return userDao.findBySQL(sql, startIdx, rows);
    }

    @Override
    public void choice(String did, List<String> uids) {
        for (String uid : uids) {
            String sql = "delete from user_dormitories ud where ud.students_id = '" + uid + "'";
            jdbcTemplate.execute(sql);
            UserDormitories userDormitories = new UserDormitories();
            userDormitories.setDormitories(dormitoriesDao.get(did));
            userDormitories.setStudents(userDao.get(uid));
            userDormitoriesDao.save(userDormitories);
        }
    }
}
